package com.microweb.toastmaster.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import com.microweb.toastmaster.webapp.action.BaseFormController;
import com.microweb.toastmaster.model.TMRole;
import com.microweb.toastmaster.service.TMRoleManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class TMRoleFormController extends BaseFormController {
    private TMRoleManager tMRoleManager = null;

    public void setTMRoleManager(TMRoleManager tMRoleManager) {
        this.tMRoleManager = tMRoleManager;
    }
    public TMRoleFormController() {
        setCommandName("tMRole");
        setCommandClass(TMRole.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        TMRole tMRole = null;

        if (!StringUtils.isEmpty(id)) {
            tMRole = tMRoleManager.getTMRole(id);
        } else {
            tMRole = new TMRole();
        }

        return tMRole;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        TMRole tMRole = (TMRole) command;
        boolean isNew = (tMRole.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            tMRoleManager.removeTMRole(tMRole.getId().toString());

            saveMessage(request, getText("tMRole.deleted", locale));
        } else {
            tMRoleManager.saveTMRole(tMRole);

            String key = (isNew) ? "tMRole.added" : "tMRole.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editTMRole.html", "id", tMRole.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
